package com.gxd.commons.config;

import java.text.*;
import java.util.Date;

/**
 * @Author:gxd
 * @Description:
 * @Date: 17:12 2018/6/29
 * @Modified By:
 */
public class CustomDateFormat extends DateFormat {

    private DateFormat dateFormat;

    private SimpleDateFormat format1 = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");

    public CustomDateFormat(DateFormat dateFormat) {
        this.dateFormat = dateFormat;
    }

    @Override
    public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) {
        return dateFormat.format(date, toAppendTo, fieldPosition);
    }

    @Override
    public Date parse(String source, ParsePosition pos) {

        Date date = null;

        try {

            date = format1.parse(source, pos);
        } catch (Exception e) {

            date = dateFormat.parse(source, pos);
        }

        return date;
    }

    /**
     * 装饰
     * @param source
     * @return
     * @throws ParseException
     */
    @Override
    public Date parse(String source) throws ParseException {

        Date date = null;

        try {

            // 先按自己的规则来
            date = format1.parse(source);
        } catch (Exception e) {

            // 不行，那就按原先的规则
            date = dateFormat.parse(source);
        }

        return date;
    }

    /**
     * 这里装饰clone方法的原因是因为clone方法在jackson中也有用到
     * @return
     */
    @Override
    public Object clone() {
        Object format = dateFormat.clone();
        return new CustomDateFormat((DateFormat) format);
    }

}
